import subprocess
import re
import pyperclip
import threading
import time
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QLineEdit, QPushButton, QComboBox, QTabWidget
from PyQt5.QtGui import QFont

class IntelligentControlSystem:
    def __init__(self):
        self.running = False
        self.previous_clipboard_text = ""
        self.search_engines = {
            "Bing": "https://www.bing.com/search?q=",
            "Google": "https://www.google.com/search?q=",
            "Baidu": "https://www.baidu.com/s?wd=",
            "Jinshan Ciba": "https://www.iciba.com/word?w=",
            "Youdao": "https://dict.youdao.com/w/eng/"
        }
        self.default_engine = "Bing"
        self.recording = False
        self.events = []
        self.keyboard_hook = None

    def open_website(self, url):
        try:
            print(f"Opening website: {url}")
            subprocess.Popen(['start', 'chrome', url], shell=True)
        except Exception as e:
            print(f"Failed to open website: {e}")

    def search_information(self, query):
        try:
            # 检查剪切板内容是否是一个网址
            if re.match(r'^https?:\/\/', query):
                print(f"Opening URL from clipboard: {query}")
                self.open_website(query)
            else:
                # # 处理多行内容
                # if '\n' in query:
                #     raise ValueError("输入内容包含多行，请输入单行内容。")
                #将多行内容转换成一行
                query = query.replace('\n', ' ')
                search_url = self.search_engines[self.default_engine] + query
                print(f"Searching for: {query} using {self.default_engine}")
                self.open_website(search_url)
        except Exception as e:
            print(f"Failed to search information: {e}")

    def get_clipboard_text(self):
        try:
            return pyperclip.paste()
        except Exception as e:
            print(f"Failed to get clipboard text: {e}")
            return ""

    def monitor_clipboard(self):
        while self.running:
            clipboard_text = self.get_clipboard_text()
            if clipboard_text and clipboard_text != self.previous_clipboard_text:
                self.previous_clipboard_text = clipboard_text
                self.search_information(clipboard_text)
            time.sleep(1)

    def start_monitoring(self):
        self.running = True
        threading.Thread(target=self.monitor_clipboard).start()

    def stop_monitoring(self):
        self.running = False

    def record_event(self, event):
        if self.recording:
            if isinstance(event, keyboard.KeyboardEvent):
                self.events.append({
                    'type': 'keyboard',
                    'event_type': event.event_type,
                    'name': event.name,
                    'time': event.time
                })
            elif isinstance(event, pyautogui.MouseEvent):
                self.events.append({
                    'type': 'mouse',
                    'event_type': event.event_type,
                    'x': event.x,
                    'y': event.y,
                    'time': event.time
                })

    def start_recording(self):
        self.recording = True
        self.events = []
        self.keyboard_hook = keyboard.hook(self.record_event)
        pyautogui.mouseInfo()  # 启动鼠标事件记录

    def stop_recording(self):
        if self.recording:
            self.recording = False
            if self.keyboard_hook:
                keyboard.unhook(self.keyboard_hook)
                self.keyboard_hook = None

    def play_events(self):
        for event in self.events:
            if event['type'] == 'keyboard':
                if event['event_type'] == 'down':
                    pyautogui.keyDown(event['name'])
                elif event['event_type'] == 'up':
                    pyautogui.keyUp(event['name'])
            elif event['type'] == 'mouse':
                if event['event_type'] == 'click':
                    pyautogui.click(event['x'], event['y'])
                elif event['event_type'] == 'move':
                    pyautogui.moveTo(event['x'], event['y'])

    def save_events(self, filename):
        with open(filename, 'w') as f:
            json.dump(self.events, f)

    def load_events(self, filename):
        with open(filename, 'r') as f:
            self.events = json.load(f)